package io.geekidea.springbootplus.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.geekidea.springbootplus.config.properties.SpringBootPlusProperties;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.controller.BaseController;
import io.geekidea.springbootplus.framework.log.annotation.Module;
import io.geekidea.springbootplus.framework.log.annotation.OperationLog;
import io.geekidea.springbootplus.framework.log.enums.OperationLogType;
import io.geekidea.springbootplus.framework.util.DownloadUtil;
import io.geekidea.springbootplus.framework.util.UploadUtil;
import io.geekidea.springbootplus.system.annotations.CurrentCarrier;
import io.geekidea.springbootplus.system.annotations.CurrentCarrierInfo;
import io.geekidea.springbootplus.system.constant.TaskStatusConstant;
import io.geekidea.springbootplus.system.entity.Customer;
import io.geekidea.springbootplus.system.entity.School;
import io.geekidea.springbootplus.system.entity.Task;
import io.geekidea.springbootplus.system.service.SchoolService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 *  控制器
 *
 * @author miko
 * @since 2020-10-10
 */
@Slf4j
@RestController
@RequestMapping("/school")
@Module("system")
@Api(value = "API", tags = {""})
public class SchoolControllerExtra extends BaseController {

    @Autowired
    private SchoolService schoolService;


    @Autowired
    private SpringBootPlusProperties springBootPlusProperties;

    /**
     * 分页列表
     */
    @GetMapping("/icon/{SchoolID}")
    @OperationLog(name = "下载文件", type = OperationLogType.download)
    @ApiOperation(value = "下载文件", notes = "下载文件", response = ApiResult.class)
    public void download(@PathVariable(required = true) String SchoolID, HttpServletResponse response) throws Exception {
        // 下载目录，既是上传目录
        String downloadDir = springBootPlusProperties.getSchoolIconPath();
        // 允许下载的文件后缀
        List<String> allowFileExtensions = springBootPlusProperties.getAllowDownloadFileExtensions();
        // 文件下载，使用默认下载处理器
        // 文件下载，使用自定义下载处理器

        School school = schoolService.getById(SchoolID);
        String schoolName = school.getSchoolName().split("\\(")[0]+".png";

        DownloadUtil.download(downloadDir, schoolName, allowFileExtensions, response, (dir, fileName, file, fileExtension, contentType, length) -> {
            // 下载自定义处理，返回true：执行下载，false：取消下载
            log.info("dir = " + dir);
            log.info("fileName = " + fileName);
            log.info("file = " + file);
            log.info("fileExtension = " + fileExtension);
            log.info("contentType = " + contentType);
            log.info("length = " + length);
            return true;
        });
    }


    /**
     * 修改
     */
    @PostMapping("/uploadIcon")
    @OperationLog(name = "修改", type = OperationLogType.UPDATE)
    @ApiOperation(value = "修改", response = ApiResult.class)
    public ApiResult<Boolean> updateTask(@RequestParam("file") MultipartFile file,
                                         @RequestParam("schoolName") String schoolName) throws Exception {

        // 上传文件，返回保存的文件名称
        String saveFileName = UploadUtil.upload(springBootPlusProperties.getSchoolIconPath(), file, originalFilename -> {
            return schoolName+".png";
        });

        School school = new School();
        school.setDeleted(1);
        school.setCreateUserID(1);
        school.setLongitude("0");
        school.setLatitude("0");

        school.setSchoolName(schoolName);
        schoolService.saveOrUpdate(school,new LambdaQueryWrapper<School>().eq(School::getSchoolName,schoolName));

        return ApiResult.result(true);
    }





    /**
     * 分页列表
     */
    @PostMapping("/search")
    @OperationLog(name = "分页列表", type = OperationLogType.PAGE)
    @ApiOperation(value = "分页列表", response = School.class)
    public ApiResult<List<School>> getSchoolPageList(@RequestBody JSONObject jsonObject) throws Exception {
        String searchText = jsonObject.getString("searchText");
        List<School> list = schoolService.list(new LambdaQueryWrapper<School>().like(School::getSchoolName,searchText));
        if(list.size()>6){
            list = list.subList(0,6);
        }
        return ApiResult.ok(list);
    }

    /**
     * 开通
     */
    @PostMapping("/open")
    @OperationLog(name = "开通", type = OperationLogType.PAGE)
    @ApiOperation(value = "开通", response = School.class)
    public ApiResult<String> open(@RequestBody JSONObject jsonObject) throws Exception {
        int schoolID = (int) jsonObject.get("schoolID");

        School school = schoolService.getById(schoolID);

        school.setDeleted(0);

        schoolService.saveOrUpdate(school);

        return ApiResult.ok("更新成功");
    }


}

